//
//  AppService.m
//  quickBatchManager
//
//  Created by 王定波 on 15/9/25.
//  Copyright © 2015年 jack. All rights reserved.
//

#import "AppService.h"

@implementation AppService


+(void) putInFactoryProduct:(NSInteger)productId andColorList:(NSArray*)colorList  andSizeList:(NSArray*)sizeList andNumberList:(NSDictionary*) selectNumber
{
    NSDate *date = [NSDate date];
    for (NSString *key in selectNumber) {
        NumberFieldModel *number=[selectNumber objectForKey:key];
        FactoryProductInfoModel *productInfo = [[FactoryProductInfoModel alloc] init];
        productInfo.productId = productId;
        productInfo.factoryProductNumber = [number.numberField.text intValue];
        productInfo.date = [DateUtils dateToStringByFormat:date format:YYYYMMDDHHMMSS];
        
        
        NSArray *cs=[key componentsSeparatedByString:@"_"];
        int cp=[cs[0] intValue]-1;
        int sp=[cs[1] intValue]-1;
        
        productInfo.sizeName=sizeList[sp];
        productInfo.colorName=colorList[cp];
        [FactoryProductInfoModel insertToDB:productInfo];
    }
    
}


+(void)updateSaleProductInfo:(NSInteger)saleOrderId andProductId:(NSInteger) productId andPductInfoId:(NSInteger) productInfoId andNumberList:(NSDictionary*) selectNumber andColorList:(NSArray*)colorList  andSizeList:(NSArray*)sizeList andSalePrices:(NSString *) salePrices
{
    double totalNumber=0;
    double totalPrice=0;

    for (NSString *key in selectNumber) {
        NumberFieldModel *number=[selectNumber objectForKey:key];
        int i = [[key getSubstringFrom:0 to:[key rangeOfString:@"_"].location] integerValue];
        int j = [[key getSubstringFrom:[key rangeOfString:@"_"].location+1 to:[key length]] integerValue];
    
        SaleOrderInfoModel *salemodel = [SaleOrderInfoModel searchSingleWithWhere:@{@"productId":[NSString stringWithFormat:@"%d",productId],@"sizeName":sizeList[j-1],@"colorName":colorList[i-1],@"saleOrderId":[ToolUtils numberToStr:saleOrderId],@"saleOrderInfoId":[NSString stringWithFormat:@"%ld",(long)productInfoId]} orderBy:nil];
        
        [AppService outInProduct:- [number.numberField.text integerValue] + salemodel.productNumber andProductId:productId andSize:salemodel.sizeName andColor:salemodel.colorName];
        
        salemodel.productNumber = [number.numberField.text integerValue];
        totalNumber+=salemodel.productNumber;
        totalPrice+=[salePrices floatValue]*salemodel.productNumber;
        [salemodel updateToDB];

    }
    
    
    [AppService updateSaleOrderTotalById:saleOrderId];
    
   
}


+(void) outInProduct:(NSInteger) number andProductId:(NSInteger)productId andSize:(NSString*)size andColor:(NSString*)color
{
    ProductInfoModel *productInfo=[ProductInfoModel searchSingleWithWhere:@{@"productId":[ToolUtils numberToStr:productId],@"sizeName":size,@"colorName":color} orderBy:nil];
    
    productInfo.productNumber+=number;
    productInfo.product.totalNumber=[ProductInfoModel sumWithWhere:@"productNumber" where:@{@"productId":[ToolUtils numberToStr:productId]}];
    
    [productInfo updateToDB];
    [productInfo.product updateToDB];
}


+(void) updateSaleOrderTotalById:(NSInteger)saleOrderId
{
    SaleOrderModel *saleOrder = [SaleOrderModel searchSingleWithWhere:@{@"saleOrderId":[ToolUtils numberToStr:saleOrderId]} orderBy:nil];
    
    
    saleOrder.orderPrice = [SaleOrderInfoModel sumWithWhere:@"productNumber*price" where:@{@"saleOrderId":[ToolUtils numberToStr:saleOrderId]}];
    saleOrder.totalNumber=[SaleOrderInfoModel sumWithWhere:@"productNumber" where:@{@"saleOrderId":[ToolUtils numberToStr:saleOrderId]}];
    saleOrder.totalPrice=saleOrder.orderPrice*saleOrder.discount;
    
    [saleOrder updateToDB];
}



+(void) putInSaleProduct:(SaleOrderModel *)saleOrder andProductId:(NSInteger) productId andBuyPrice:(NSString *)buyPrice andColorList:(NSArray*)colorList  andSizeList:(NSArray*)sizeList andNumberList:(NSDictionary*) selectNumber andSalePrices:(NSString *) salePrices
{
    //添加单据
     saleOrder = [AppService getSaleOrderByNo:saleOrder.saleOrderNo];
    
    
    double totalNumber=0;
    double totalPrice=0;

    int y = (arc4random() % 101) + 25000;
    for (NSString *key in selectNumber) {
        NumberFieldModel *number=[selectNumber objectForKey:key];
        SaleOrderInfoModel *productInfo = [[SaleOrderInfoModel alloc] init];
        productInfo.saleOrderInfoId = y;
        productInfo.saleOrderId = saleOrder.saleOrderId;
        productInfo.productId = productId;
        productInfo.productNumber = [number.numberField.text intValue];
        NSLog(@"productNumber:%d",productInfo.productNumber);
        productInfo.price=productInfo.product.salePrice;
        totalNumber+=productInfo.productNumber;
        totalPrice+=[salePrices floatValue]*productInfo.productNumber;
        
        
        NSArray *cs=[key componentsSeparatedByString:@"_"];
        int cp=[cs[0] intValue]-1;
        int sp=[cs[1] intValue]-1;
        
        productInfo.sizeName=sizeList[sp];
        productInfo.colorName=colorList[cp];

        [SaleOrderInfoModel insertToDB:productInfo];
        
        ProductInfoModel *model=[ProductInfoModel searchSingleWithWhere:@{@"productId":[ToolUtils numberToStr:productId],@"sizeName":productInfo.sizeName,@"colorName":productInfo.colorName} orderBy:nil];
        int n = -productInfo.productNumber + model.productNumber;
        model.productNumber = n;
        model.product.totalNumber=[ProductInfoModel sumWithWhere:@"productNumber" where:@{@"productId":[ToolUtils numberToStr:productId]}];
        
        [model updateToDB];
        [model.product updateToDB];
        
    }
    
    [AppService updateSaleOrderTotalById:saleOrder.saleOrderId];
}

//添加一个入库
+(BatchProductModel*) putInProduct:(NSString *)modelNo andBatch:(BatchProductModel *)batch andCategory:(CategoryModel *)category andBuyPrice:(NSString *)buyPrice andSalePrice:(NSString *)salePrice andImage:(UIImage*) image andPicPath:(NSString*)picPath andColorSizeView:(NumberFieldView *)colorSizeView
{
    
    //保存图片
    if((picPath==nil || [picPath isBlank]) && image)
    {
        picPath=[ToolUtils saveImageToLocal:image];
    }
    else if(picPath==nil)
    {
        picPath=@"";
    }
    
    
    NSString *date=[DateUtils dateToStringByFormat:[NSDate date] format:YYYYMMDDHHMMSS];
    
    //判断产品是否存在
    ProductModel *pinfo=[AppService getProductByNo:modelNo];
    if(pinfo)
    {
        pinfo.categoryId=category.categoryId;
        pinfo.buyPrice=[buyPrice floatValue];
        pinfo.salePrice=[salePrice floatValue];
        pinfo.photo=picPath;
        
        pinfo.updateDate=date;
        [pinfo updateToDB];
    }
    else
    {
        pinfo=[[ProductModel alloc] init];
        pinfo.categoryId=category.categoryId;
        pinfo.modelNo=modelNo;
        pinfo.buyPrice=[buyPrice floatValue];
        pinfo.salePrice=[salePrice floatValue];
        pinfo.photo=picPath;
        pinfo.name=@"";
        
        pinfo.totalNumber=0;
        pinfo.createDate=date;
        pinfo.updateDate=date;
        [ProductModel insertToDB:pinfo];
        pinfo=[AppService getProductByNo:modelNo];
        
    }
    
    pinfo.isImageUpload = NO;
    
    //删除已经添加的
    [AddProductModel deleteWithWhere:@{@"batchId":[ToolUtils numberToStr:batch.batchId],@"productId":[ToolUtils numberToStr:pinfo.productId]}];
    double totalPrice=0;
    double totalNumber=0;
    
    
    
    for (NSString *key in colorSizeView.selectNumber) {
        NumberFieldModel *number=[colorSizeView.selectNumber objectForKey:key];
        AddProductModel *apinfo=[[AddProductModel alloc] init];
        apinfo.productId=pinfo.productId;
        apinfo.batchId=batch.batchId;
        apinfo.productNumber=[number.numberField.text intValue];
        apinfo.createDate=date;
        apinfo.updateDate=date;
        apinfo.buyPrice=[buyPrice floatValue];
        apinfo.salePrice=[salePrice floatValue];
        apinfo.photo=picPath;
        
        totalPrice+=apinfo.buyPrice*apinfo.productNumber;
        totalNumber+=apinfo.productNumber;
        
        int sp=([key intValue]-1)%100-1;
        int cp=([key intValue]-1-sp)/100-1;
        
        
        apinfo.sizeName=colorSizeView.sizeList[sp];
        apinfo.colorName=colorSizeView.colorList[cp];
        apinfo.remark=@"";
        
        [AddProductModel insertToDB:apinfo];
        
         //添加到附属
        ProductInfoModel *pi=[ProductInfoModel searchSingleWithWhere:@{@"productId":[ToolUtils numberToStr:apinfo.productId],@"sizeName":apinfo.sizeName,@"colorName":apinfo.colorName} orderBy:nil];
        if(pi)
        {
            pi.productNumber+=apinfo.productNumber;
            [pi updateToDB];
        }
        else
        {
            pi=[[ProductInfoModel alloc] init];
            pi.sizeName=apinfo.sizeName;
            pi.colorName=apinfo.colorName;
            pi.productId=apinfo.productId;
            pi.productNumber=apinfo.productNumber;
            [ProductInfoModel insertToDB:pi];
        }
        
    }
    
    batch.batchPrice=[AddProductModel sumWithWhere:@"productNumber*buyPrice" where:@{@"batchId":[ToolUtils numberToStr:batch.batchId]}];
    batch.updateDate=date;
    batch.totalNumber= totalNumber;
    batch.batchPrice = batch.batchPrice*batch.discount;
    batch.totalPrice=batch.batchPrice                                                                                                                             ;
    [batch updateToDB];
    
    return batch;
}

//结束批次
+(void)overBatchProduct:(BatchProductModel*)batch
{
    batch=[AppService getBatchProductById:batch.batchId];
    NSArray *addplist=[AddProductModel searchWithWhere:@{@"batchId":[ToolUtils numberToStr:batch.batchId]}];
    double totalPrice=0;
    double totalNumber=0;
    NSString *date=[DateUtils dateToStringByFormat:[NSDate date] format:YYYYMMDDHHMMSS];
    for (AddProductModel *ap in addplist) {
        
        totalPrice+=ap.salePrice*ap.productNumber;
        totalNumber+=ap.productNumber;
        
        ap.product.updateDate=date;
        ap.product.totalNumber+=ap.productNumber;
        [ap.product updateToDB];
        
        //添加到附属
//        ProductInfoModel *pi=[ProductInfoModel searchSingleWithWhere:@{@"productId":[ToolUtils numberToStr:ap.productId],@"sizeName":ap.sizeName,@"colorName":ap.colorName} orderBy:nil];
//        if(pi)
//        {
//            pi.productNumber+=ap.productNumber;
//            [pi updateToDB];
//        }
//        else
//        {
//            pi=[[ProductInfoModel alloc] init];
//            pi.sizeName=ap.sizeName;
//            pi.colorName=ap.colorName;
//            pi.productId=ap.productId;
//            pi.productNumber=ap.productNumber;
//            [ProductInfoModel insertToDB:pi];
//        }
        
    }
    
    
    
    batch.batchPrice=[AddProductModel sumWithWhere:@"productNumber*buyPrice" where:@{@"batchId":[ToolUtils numberToStr:batch.batchId]}];
    batch.updateDate=date;
    batch.totalNumber=totalNumber;
    batch.batchPrice = batch.batchPrice*batch.discount;
    batch.totalPrice=batch.batchPrice;
    
    batch.isOver=YES;
    [batch updateToDB];
    
}

+(BatchProductModel *)getBatchProductByDate:(NSDate*)date
{
    if(date==nil)
        date=[NSDate date];
    NSString *batch=[DateUtils dateToStringByFormat:[NSDate date] format:@"yyyyMMdd"];
    BatchProductModel *binfo=[BatchProductModel searchSingleWithWhere:[NSString stringWithFormat:@"batchNo LIKE '%@%%' and isOver=0",batch] orderBy:nil];
    
    if(binfo)
        return binfo;
    
    NSInteger pcount=[BatchProductModel rowCountWithWhere:nil];
    NSString *batchNo=[NSString stringWithFormat:@"%@%06d",batch,pcount+1];
    binfo=[self getBatchProductByNo:batchNo];
    return binfo;
}

+(SaleOrderModel *)getNewSaleOrder
{
    [SaleOrderModel deleteWithWhere:@"totalNumber=0"];
    NSString *batch=[DateUtils dateToStringByFormat:[NSDate date] format:@"yyyyMMddhhmmss"];
    SaleOrderModel *binfo=[SaleOrderModel searchSingleWithWhere:[NSString stringWithFormat:@"saleOrderNo LIKE '%@%%' And totalNumber=0",batch] orderBy:nil];
    
    if(binfo)
     return binfo;
    
    NSInteger pcount=[BatchProductModel rowCountWithWhere:nil];
    NSString *batchNo=[NSString stringWithFormat:@"%@%06d",batch,pcount+1];
    binfo=[self getSaleOrderByNo:batchNo];
    return binfo;

}


+(NSArray*)searchProductByKeyWord:(NSString*)keyword
{
    return [ProductModel searchWithWhere:[NSString stringWithFormat:@"modelNo LIKE '%@%%%%'",keyword]];
}



/**
 根据型号获取尺寸和颜色
 **/
+(NSDictionary*)getSizeAndColorByModel:(NSString*)model
{
    
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] init];
    NSMutableArray *colorlist=[[NSMutableArray alloc] init];
    NSMutableArray *sizelist=[[NSMutableArray alloc] init];
    
   
    
    ProductModel *product=[AppService getProductByNo:model];
    [dic setObject:colorlist forKey:@"color"];
    [dic setObject:sizelist forKey:@"size"];
    
    
    
    NSArray *sizeList=[ProductInfoModel searchWithWhere:@{@"productId":[ToolUtils numberToStr:product.productId]} orderBy:nil groupBy:@"sizeName" offset:0 count:0];
    NSArray *colorList=[ProductInfoModel searchWithWhere:@{@"productId":[ToolUtils numberToStr:product.productId]} orderBy:nil groupBy:@"colorName" offset:0 count:0];
    
    
    for (ProductInfoModel *pinfo in colorList) {
        [colorlist addObject:pinfo.colorName];
    }
    
    for (ProductInfoModel *pinfo in sizeList) {
        [sizelist addObject:pinfo.sizeName];
    }
    return dic;
}




+(BatchProductModel *)getBatchProductByNo:(NSString*)batchNo
{
    NSString *date=[DateUtils dateToStringByFormat:[NSDate date] format:YYYYMMDDHHMMSS];
    BatchProductModel *binfo=[BatchProductModel searchSingleWithWhere:@{@"batchNo":batchNo} orderBy:nil];
    if(!binfo)
    {
        binfo=[[BatchProductModel alloc] init];
        binfo.batchNo=batchNo;
        binfo.isPay=0;
        binfo.payType=0;
        binfo.createDate=date;
        binfo.updateDate=date;
        binfo.remark=@"";
        binfo.discount=1;
        binfo.paidPrice=0;
        binfo.unpaidPrice=0;
        binfo.moLingPrice=0;
        binfo.deptPrice=0;
        [BatchProductModel insertToDB:binfo];
        
        return [self getBatchProductByNo:batchNo];
    }
    
    
    return binfo;
}


+(SaleOrderModel *)getSaleOrderByNo:(NSString*)saleOrderNo
{
    NSString *date=[DateUtils dateToStringByFormat:[NSDate date] format:YYYYMMDDHHMMSS];
    SaleOrderModel *binfo=[SaleOrderModel searchSingleWithWhere:@{@"saleOrderNo":saleOrderNo} orderBy:nil];
    if(!binfo)
    {
        binfo=[[SaleOrderModel alloc] init];
        binfo.saleOrderNo=saleOrderNo;
        binfo.isPay=0;
        binfo.payType=0;
        binfo.date=date;
        binfo.remark=@"";
        binfo.discount=1;
        binfo.paidPrice=0;
        binfo.unpaidPrice=0;
        binfo.moLingPrice=0;
        binfo.deptPrice=0;
        [SaleOrderModel insertToDB:binfo];
        
        return [self getSaleOrderByNo:saleOrderNo];
    }
    
    
    return binfo;
}



+(SupplierModel*)getSupplyByBatchNo:(NSString*)batchNo
{
    BatchProductModel *binfo=[BatchProductModel searchSingleWithWhere:@{@"batchNo":batchNo} orderBy:nil];
    
    if(binfo)
        return [SupplierModel searchSingleWithWhere:@{@"supplierId":[NSString stringWithFormat:@"%d",binfo.supplierId]} orderBy:nil];
    else return nil;
}

+(double)getAmountByUserIdAndType:(NSInteger)userId andType:(AccountType) accountType
{
    double total=0;
    NSMutableString *where=[[NSMutableString alloc] initWithString:@"1=1"];
    switch (accountType) {
        case AccountTypeSupplier:
            
            if(userId>0)
            {
                [where appendFormat:@" And supplierId='%d'",userId];
            }
            //批次欠款
            double batchtotal=[BatchProductModel sumWithWhere:@"totalPrice-moLingPrice-paidPrice" where:[NSString stringWithFormat:@"%@ and isPay='0'",where]];
            
            double paytotal=[PayOutModel sumWithWhere:@"amount" where:[NSString stringWithFormat:@"%@",where]];
            
            total=batchtotal-paytotal;
            
            break;
        case AccountTypeClient:
        case AccountTypeAllocate:
            if(userId>0)
            {
                [where appendFormat:@" And clientId='%d'",userId];
            }
            else
            {
                NSArray *list=[ClientModel searchWithWhere:[NSString stringWithFormat:@"clientType=%d",accountType==AccountTypeClient?0:1]];
                
                if(list.count>0)
                {
                    [where appendString:@" And clientId in("];
                    for (int i=0; i<list.count; i++) {
                        ClientModel *client=[list objectAtIndex:i];
                        if(i==list.count-1)
                        [where appendFormat:@"%d",client.clientId];
                        else [where appendFormat:@"%d,",client.clientId];
                    }
                    [where appendString:@")"];
                }

            }
            
            double ordertotal=[SaleOrderModel sumWithWhere:@"totalPrice-moLingPrice-paidPrice" where:[NSString stringWithFormat:@"%@ and isPay='0'",where]];
            double payintotal=[PayInModel sumWithWhere:@"amount" where:[NSString stringWithFormat:@"%@",where]];
            total=ordertotal-payintotal;

        default:
            break;
    }
    
    
    
    return total;
}

+(double)getAmountByUserIdAndDateAndType:(NSInteger)userId  andDate:(NSString*)date andType:(AccountType) accountType
{
    double total=0;
    NSMutableString *where=[[NSMutableString alloc] initWithString:@"1=1"];
    switch (accountType) {
        case AccountTypeSupplier:
            
            if(userId>0)
            {
                [where appendFormat:@" And supplierId='%d'",userId];
            }
            //批次欠款
            double batchtotal=[BatchProductModel sumWithWhere:@"totalPrice-moLingPrice-paidPrice" where:[NSString stringWithFormat:@"%@ and isPay='0' and createDate<='%@'",where,date]];
            
            double paytotal=[PayOutModel sumWithWhere:@"amount" where:[NSString stringWithFormat:@"%@ and payDate<='%@'",where,date]];
            
            total=batchtotal-paytotal;
            
            break;
        case AccountTypeClient:
        case AccountTypeAllocate:
            if(userId>0)
            {
                [where appendFormat:@" And clientId='%d'",userId];
            }
            else
            {
                NSArray *list=[ClientModel searchWithWhere:[NSString stringWithFormat:@"clientType=%d",accountType==AccountTypeClient?0:1]];
                
                if(list.count>0)
                {
                    [where appendString:@" And clientId in("];
                    for (int i=0; i<list.count; i++) {
                        ClientModel *client=[list objectAtIndex:i];
                        if(i==list.count-1)
                            [where appendFormat:@"%d",client.clientId];
                        else [where appendFormat:@"%d,",client.clientId];
                    }
                    [where appendString:@")"];
                }
                
            }
            
            double ordertotal=[SaleOrderModel sumWithWhere:@"totalPrice-moLingPrice-paidPrice" where:[NSString stringWithFormat:@"%@ and isPay='0' and date<='%@'",where,date]];
            double payintotal=[PayInModel sumWithWhere:@"amount" where:[NSString stringWithFormat:@"%@ and payDate<='%@'",where,date]];
            total=ordertotal-payintotal;
            
        default:
            break;
    }
    
    
    
    return total;
}


+(double)getSupplierTotalNumberById:(NSInteger)supplierId
{
    double batchtotal=[BatchProductModel sumWithWhere:@"totalNumber" where:[NSString stringWithFormat:@"supplierId='%d'",supplierId]];
    
    
    return batchtotal;
}


+(NSArray*)getBatchListById:(NSInteger)supplierId  andStartDate:(NSString*)startdate andEndDate:(NSString*)enddate
{
    return [BatchProductModel searchWithWhere:[NSString stringWithFormat:@"supplierId='%d' %@ %@",supplierId,startdate?[NSString stringWithFormat:@" and createDate>='%@'",startdate]:@"",enddate?[NSString stringWithFormat:@" and createDate<='%@'",enddate]:@""]];
}


+(NSArray*)getOrderListById:(NSInteger)clientId  andStartDate:(NSString*)startdate andEndDate:(NSString*)enddate
{
    return [SaleOrderModel searchWithWhere:[NSString stringWithFormat:@"clientId='%d' %@ %@",clientId,startdate?[NSString stringWithFormat:@" and date>='%@'",startdate]:@"",enddate?[NSString stringWithFormat:@" and date<='%@'",enddate]:@""]];
}


+(NSArray*)getPayOutListById:(NSInteger)supplierId  andStartDate:(NSString*)startdate andEndDate:(NSString*)enddate
{
    return [PayOutModel searchWithWhere:[NSString stringWithFormat:@"supplierId='%d' %@ %@",supplierId,startdate?[NSString stringWithFormat:@" and payDate>='%@'",startdate]:@"",enddate?[NSString stringWithFormat:@" and payDate<='%@'",enddate]:@""]];
}
+(NSArray*)getPayInListById:(NSInteger)clientId  andStartDate:(NSString*)startdate andEndDate:(NSString*)enddate;
{
    return [PayInModel searchWithWhere:[NSString stringWithFormat:@"clientId='%d' %@ %@",clientId,startdate?[NSString stringWithFormat:@" and payDate>='%@'",startdate]:@"",enddate?[NSString stringWithFormat:@" and payDate<='%@'",enddate]:@""]];
}


+(NSArray*)getClearPriceListByClientId:(NSInteger)clientId  andStartDate:(NSString*)startdate andEndDate:(NSString*)enddate
{
    return [ClearPriceModel searchWithWhere:[NSString stringWithFormat:@"clientId='%d' %@ %@",clientId,startdate?[NSString stringWithFormat:@" and clearDate>='%@'",startdate]:@"",enddate?[NSString stringWithFormat:@" and clearDate<='%@'",enddate]:@""]];
}
+(NSArray*)getClearPriceListBySupplierId:(NSInteger)SupplierId  andStartDate:(NSString*)startdate andEndDate:(NSString*)enddate
{
    return [ClearPriceModel searchWithWhere:[NSString stringWithFormat:@"supplierId='%d' %@ %@",SupplierId,startdate?[NSString stringWithFormat:@" and clearDate>='%@'",startdate]:@"",enddate?[NSString stringWithFormat:@" and clearDate<='%@'",enddate]:@""]];
}



+(NSArray*)getOrderListByDate:(QbType)qbtype andStartDate:(NSString*)startdate andEndDate:(NSString*)enddate
{

    NSMutableString *where=[[NSMutableString alloc] initWithString:@"1=1 and isArchive =1"];
    NSArray *list=[ClientModel searchWithWhere:[NSString stringWithFormat:@"clientType=%d",qbtype==QbTypeSale?0:1]];
    
    if(list.count>0)
    {
        [where appendString:@" and clientId in("];
        if(qbtype==QbTypeSale)
        {
             [where appendFormat:@"%d,",0];
        }
        for (int i=0; i<list.count; i++) {
            ClientModel *client=[list objectAtIndex:i];
            if(i==list.count-1)
            {
                [where appendFormat:@"%d",client.clientId];
            }
            else
            {
                [where appendFormat:@"%d,",client.clientId];
            }
        }
        [where appendString:@")"];
    }else
    {
        if(qbtype==QbTypeSale)
        {
            [where appendString:@" and clientId =0"];
        }else
        {
            [where appendString:@" and 1=0"];
        }
    }
    NSLog(@"where:%@",where);
    return [SaleOrderModel searchWithWhere:[NSString stringWithFormat:@"%@ %@ %@",where,startdate?[NSString stringWithFormat:@" and date>='%@ 00:00:00'",startdate]:@"",enddate?[NSString stringWithFormat:@" and date<='%@ 23:59:59'",enddate]:@""]  orderBy:@"date desc" offset:0 count:0];
}





+(NSArray*)getBatchListByDate:(NSString*)startdate andEndDate:(NSString*)enddate
{
    return [BatchProductModel searchWithWhere:[NSString stringWithFormat:@" isOver=1 %@ %@",startdate?[NSString stringWithFormat:@" and createDate>='%@ 00:00:00'",startdate]:@"",enddate?[NSString stringWithFormat:@" and createDate<='%@ 23:59:59'",enddate]:@""] orderBy:@"createDate desc" offset:0 count:0];
}


+(ProductModel*)getProductById:(NSInteger)productId
{
    ProductModel *product=[ProductModel searchSingleWithWhere:@{@"productId":[ToolUtils numberToStr:productId]} orderBy:nil];
    return product;
}

+(ProductModel*)getProductByNo:(NSString*)modelNo
{
    ProductModel *product=[ProductModel searchSingleWithWhere:@{@"modelNo":modelNo} orderBy:nil];
    return product;
}


+(BatchProductModel*)getBatchProductById:(NSInteger)batchId
{
    BatchProductModel *product=[BatchProductModel searchSingleWithWhere:@{@"batchId":[ToolUtils numberToStr:batchId]} orderBy:nil];
    return product;
}

+(void)delProductById:(NSInteger)productId
{
    ProductModel *product=[AppService getProductById:productId];
    product.isDel=YES;
    product.modelNo=[NSString stringWithFormat:@"%@(已删除)",product.modelNo];
    product.updateDate = [DateUtils dateToStringByFormat:[NSDate date] format:YYYYMMDDHHMMSS];
    
    [product updateToDB];
    
    
}



+(void) editProductById:(NSInteger)productId andModel:(NSString *)modelNo andCategory:(CategoryModel *)category andBuyPrice:(NSString *)buyPrice andSalePrice:(NSString *)salePrice andImage:(UIImage*) image andPicPath:(NSString*)picPath andColorSizeView:(NumberFieldView *)colorSizeView
{
    ProductModel *product=[AppService getProductById:productId];
    if([modelNo isValid])
    {
        product.modelNo=modelNo;
    }
    product.salePrice=[salePrice floatValue];
    product.buyPrice=[buyPrice floatValue];
    product.categoryId=category.categoryId;
    
    //保存图片
    if((picPath==nil || [picPath isBlank]) && image)
    {
        picPath=[ToolUtils saveImageToLocal:image];
    }
    else if(picPath==nil)
    {
        picPath=@"";
    }
    
    product.photo=picPath;
    product.isImageUpload = NO;

    double totalNumber=0;
    
    
    [ProductInfoModel deleteWithWhere:@{@"productId":[ToolUtils numberToStr:productId]}];
    
    for (NSString *key in colorSizeView.selectNumber) {
        NumberFieldModel *number=[colorSizeView.selectNumber objectForKey:key];
        
        ProductInfoModel *apinfo=[[ProductInfoModel alloc] init];
        apinfo.productId=productId;
        apinfo.productNumber=[number.numberField.text intValue];
        
        
        int sp=([key intValue]-1)%100-1;
        int cp=([key intValue]-1-sp)/100-1;
        
        
        apinfo.sizeName=colorSizeView.sizeList[sp];
        apinfo.colorName=colorSizeView.colorList[cp];
        
        totalNumber+=apinfo.productNumber;
        
        [ProductInfoModel insertToDB:apinfo];
        
    }
   
    product.totalNumber=totalNumber;
    
    

    [product updateToDB];
    
}


+(NSArray*)getProductNumListById:(NSInteger)productId andColorList:(NSArray*)colorList  andSizeList:(NSArray*)sizeList
{
    NSMutableArray *numData=[[NSMutableArray alloc] init];
    for (NSString *color in colorList) {
        NSMutableArray *rowData=[[NSMutableArray alloc] init];
        [numData addObject:rowData];
        for (NSString *size in sizeList) {
            ProductInfoModel *s=[ProductInfoModel searchSingleWithWhere:@{@"productId":[ToolUtils numberToStr:productId],@"sizeName":size,@"colorName":color} orderBy:nil];
            [rowData addObject:[ToolUtils numberToStr:s.productNumber]];
            
        }
    }
    return numData;
}

@end
